package com.bootdo.common.service.impl;

import com.bootdo.common.dao.GenTableColumnDao;
import com.bootdo.common.domain.GenTableColumnDO;
import com.bootdo.common.utils.GenUtils1;
import com.bootdo.common.utils.text.Constants;
import com.bootdo.common.utils.text.StringUtils;
import com.bootdo.common.utils.text.VelocityInitializer;
import com.bootdo.common.utils.text.VelocityUtils;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.bootdo.common.dao.GenTableDao;
import com.bootdo.common.domain.GenTableDO;
import com.bootdo.common.service.GenTableService;


@Service
public class GenTableServiceImpl implements GenTableService {
    @Autowired
    private GenTableDao genTableDao;

    @Autowired
    private GenTableColumnDao genTableColumnDao;

    @Override
    public GenTableDO get(Long tableId) {
        return genTableDao.get(tableId);
    }

    @Override
    public byte[] generatorCode(String tableName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }


    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableName, ZipOutputStream zip)
    {
        // 查询表信息
        GenTableDO table = genTableDao.selectGenTableByName(tableName);
//        table.setClassname(org.apache.commons.lang.StringUtils.uncapitalize(table.getClassName()));
        // 查询列信息
        List<GenTableColumnDO> columns = table.getColumns();
        setPkColumn(table, columns);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate("templates/" + template, Constants.UTF8);
            tpl.merge(context, sw);
            try
            {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, Constants.UTF8);
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置主键列信息
     *
     * @param columns 业务字段列表
     */
    public void setPkColumn(GenTableDO table, List<GenTableColumnDO> columns)
    {
        for (GenTableColumnDO column : columns)
        {
            if (column.isPk())
            {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn()))
        {
            table.setPkColumn(columns.get(0));
        }
    }

    @Override
    public List<GenTableDO> list(Map<String, Object> map) {
        return genTableDao.list(map);
    }

    @Override
    public List<GenTableDO> selectDbTableListByNames(String[] tableNames) {
        return genTableDao.selectDbTableListByNames(tableNames);
    }

    @Override
    public void importGenTable(List<GenTableDO> tableList) {
        for (GenTableDO table : tableList) {
            try {
                String tableName = table.getTableName();
                GenUtils1.initTable(table);
                int row = genTableDao.save(table);
                if (row > 0) {
                    // 保存列信息
                    List<GenTableColumnDO> genTableColumns = genTableColumnDao.selectDbTableColumnsByName(tableName);
                    for (GenTableColumnDO column : genTableColumns) {
                        GenUtils1.initColumnField(column, table);
                        genTableColumnDao.save(column);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<GenTableDO> selectDbTableList(Map<String, Object> map) {
        return genTableDao.selectDbTableList(map);
    }

    @Override
    public int countSelectDbTableList(Map<String, Object> map) {
        return genTableDao.countSelectDbTableList(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return genTableDao.count(map);
    }

    @Override
    public int save(GenTableDO genTable) {
        return genTableDao.save(genTable);
    }

    @Override
    public int update(GenTableDO genTable) {

        int row = genTableDao.update(genTable);
        if (row > 0) {
            for (GenTableColumnDO cenTableColumn : genTable.getColumns()) {
                genTableColumnDao.update(cenTableColumn);
            }
        }
        return row;
    }

    @Override
    public int remove(Long tableId) {
        return genTableDao.remove(tableId);
    }

    @Override
    public int batchRemove(Long[] tableIds) {
        return genTableDao.batchRemove(tableIds);
    }

}
